<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FreeEngine_文件上传</title>
</head>

<style>

    html, body {
        height: 100%;
    }

</style>

<body>

    <div style="width: 400px; height: 50%; margin: auto;">

        <div>
            UUID: <span id="span_uuid">-</span>
        </div>
        <div style="height: 5%;"></div>
        <div id="div_file_drop" draggable="true" style="border: 1px solid black; border-radius: 5px; height: 50%;
        text-align: justify; display: flex; align-items: center; justify-content: center;
        background-color: #ADADAD;">
            拖拽文件到这里
        </div>
        <div style="height: 2%;"></div>
        <div>
            <input type="file" id="files" style="display: none" onchange="fileImport();">
            <input type="button" id="fileImport" value="选择文件" onclick="openFileImport()" style="width: 100%;">
        </div>
        <div style="height: 2%;"></div>
        <div>
            <div id="div_file_name">--</div>
            <div style="height: 5px;"></div>
            <div id="div_translate_progress_bar_wrapper" style="height: 7px; border-radius: 4px; background-color: gray;">
                <div id="div_translate_progress_bar" style="width: 0; height: 7px; border-radius: 4px;background-color: aqua;"></div>
            </div>
            <div><span id="span_translate_progress_number">0</span>% <span id="span_translate_progress_size">0</span>Byte</div>
        </div>
        <div style="height: 2%;"></div>
        <div id="div_message"></div>

    </div>

</body>

<script>

    var responseMessage = {
        type: -1,
        content: ""
    };

    var requestMessage = {
        type: -1,
        content: ""
    };

    var requestUpload = {
        id: "terry deng",
        name: "",
        size: 0,
    };

    var requestHostName = window.location.hostname;
    var requestWsPort = parseInt(window.location.port) + 1;
    var wsUrl = "ws://" + requestHostName + ":" + requestWsPort + "/wspath/upload";

</script>

<script>

    var currentFileData = ArrayBuffer;
    var ws = null;
    var uuid = "";
    var status = 0;
    var currentFileName = "";

    if("WebSocket" in window){
　　　　console.log("您的浏览器支持WebSocket");

　　　　ws = new WebSocket(wsUrl); //创建WebSocket连接
　　　　
        //申请一个WebSocket对象，参数是服务端地址，同http协议使用http://开头一样，WebSocket协议的url使用ws://开头，另外安全的WebSocket协议使用wss://开头
        ws.onopen = function(){
        　　//当WebSocket创建成功时，触发onopen事件
            console.log("open");
            document.getElementById("div_message").innerText = "等待服务端授权...";
        }
        ws.onmessage = function(e){
        　　//当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
        　　console.log(e.data);
            var response = JSON.parse(e.data);
            switch(response.type){
                case 0: {// 拒绝连接
                    console.log("回复: " + response.content);
                    window.alert("拒绝连接, 重试请刷新页面。");
                    document.getElementById("div_message").innerText = "服务端拒绝。";
                }break;
                case 1: {// 得到uuid
                    console.log("get uuid: " + response.content);
                    uuid = response.content;
                    document.getElementById("span_uuid").innerText = uuid;
                    status = 1;
                }break;
                case 2: {// 授权回复
                    document.getElementById("div_message").innerText = "服务端已授权。";
                }break;
                case 3: {// 开始发送文件
                    uploadFile(ws, currentFileData);
                    window.alert("文件发送完成：" + currentFileName);
                    currentFileData = null;
                    currentFileName = "";
                }break;
                default:
            }
        }
        ws.onclose = function(e){
        　　//当客户端收到服务端发送的关闭连接请求时，触发onclose事件
        　　console.log("close");
        }
        ws.onerror = function(e){
        　　//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
        　　console.log("error");
        }
　　}else{
　　　　console.log("您的浏览器不支持WebSocket");
　　}

    function getUUID(){
        return uuid;
    }

    function wsSend(callback){

        if (status == 0){
            console.log("waitting auth...");
            return;
        }

        callback();
    }

    // 1-发送文件信息
    function requestUploadFile(wsInstance, uuidx, name, size){
        if(wsInstance != null){
            var data = {
                id: uuidx,
                name: name,
                size: size,
            };

            var request = {
                type: 1,
                content: JSON.stringify(data)
            };

            currentFileName = name;

            resetTranslateProgress();

            setHTMLTagText("div_file_name", name);

            wsInstance.send(JSON.stringify(request));
        }
    }

     // 2-开始传输文件
    function uploadFile(wsInstance, fileData){
        var length = fileData.byteLength;
        var start = 0;
        var interval = 1024;
        var end = start + interval;

        console.log("file upload start");
        while(end <= length){
            var d = fileData.slice(start, end);
            wsInstance.send(d);
            
            setTranslateProgress(length, end);

            for(i = 0; i < 1000000; i++);

            start = end;
            end = start + interval;
        }
        if(end > length){
            var d = fileData.slice(start);
            wsInstance.send(d);
            setTranslateProgress(length, length);
        }

        var request = {
            type: 2,
            content: ""
        };

        wsInstance.send(JSON.stringify(request));
        console.log("file upload end");
    }

    function resetTranslateProgress(){
        setHTMLTagText("span_translate_progress_size", 0);
        setHTMLTagText("span_translate_progress_number", 0);
        document.getElementById("div_translate_progress_bar").style.width = 0;
    }

    function setTranslateProgress(allLength, currentLength){

        setHTMLTagText("span_translate_progress_size", currentLength);
        setHTMLTagText("span_translate_progress_number", (currentLength / allLength * 1.0).toFixed(2) * 100);
        
        // console.log("current length: " + (currentLength / allLength * 1.0).toFixed(2) * 100);

        var barWidth = document.getElementById("div_translate_progress_bar_wrapper").offsetWidth;
        var barCurrentWidth = ((currentLength / allLength * 1.0).toFixed(2)) * barWidth;
        // console.log("bar length: " + barCurrentWidth);
        document.getElementById("div_translate_progress_bar").style.width = barCurrentWidth + "px";
        
        
    }

    function openFileImport(){
        document.getElementById("files").click();
    }
    // 0-得到本地文件信息
    function fileImport() {
        //获取读取我文件的File对象
        var selectedFile = document.getElementById('files').files[0];
        var name = selectedFile.name; //读取选中文件的文件名
        var size = selectedFile.size; //读取选中文件的大小

        console.log("文件名:" + name + "大小:" + size);

        var reader = new FileReader(); //这是核心,读取操作就是由它完成.
        reader.readAsArrayBuffer(selectedFile);
        reader.onload = function() {
            //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
            console.log(this.result);
            console.log(this.result.byteLength);

            wsSend(function() {
                requestUploadFile(ws, getUUID(), name, size)
            });
            currentFileData = this.result;
            document.getElementById("files").value = null;
        }
    }

    function setHTMLTagText(id, txt){
        document.getElementById(id).innerText = txt;
    }
    
    //拖拽进入
    document.getElementById("div_file_drop").addEventListener("dragenter", function () {
        document.getElementById("div_file_drop").innerText = "请松手";
        document.getElementById("div_file_drop").style.backgroundColor = "#5B5B5B";
    }, false);
    //拖拽离开
    document.getElementById("div_file_drop").addEventListener("dragleave", function () {
        document.getElementById("div_file_drop").innerText = "拖拽文件到这里" ;
        document.getElementById("div_file_drop").style.backgroundColor = "#ADADAD";
    }, false);
    document.ondragover = function (e) {
        e.preventDefault();  //只有在ondragover中阻止默认行为才能触发 ondrop 而不是 ondragleave
    };
    document.ondrop = function (e) {
        e.preventDefault();  //阻止 document.ondrop的默认行为  *** 在新窗口中打开拖进的图片
    };
    document.getElementById("div_file_drop").addEventListener("drop", function (ev) {
        ev.preventDefault();//取消事件的默认动作。
        document.getElementById("div_file_drop").innerText = "拖拽文件到这里" ;
        document.getElementById("div_file_drop").style.backgroundColor = "#ADADAD";
        let fileReader = new FileReader() ;
        let file = ev.dataTransfer.files[0] ;

        var name = file.name; //读取选中文件的文件名
        var size = file.size; //读取选中文件的大小
        console.log("文件名:" + name + "大小:" + size);

        fileReader.readAsArrayBuffer(file);
        fileReader.onload = function(){
            wsSend(function() {
                requestUploadFile(ws, getUUID(), name, size)
            });
            currentFileData = this.result;
        };
        fileReader.onerror = function(){
            window.alert("文件读取错误：" + name)
        };
    }, false);


</script>

</html>